package com.htsk.city.services.wechat.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.htsk.city.services.core.entity.R;
import com.htsk.city.services.core.exception.ServiceException;
import com.htsk.city.services.core.utils.MimeTypeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;

/**
 * @Author：mjiaxing
 * @CreateTime：2023-04-03
 * @Description：文件处理
 * @Version：1.0.0
 */
@Service
@Slf4j
public class FileService {

    /**
     * 资源映射路径 前缀
     */
    @Value("${application.file.prefix}")
    public String localFilePrefix;

    /**
     * 域名或本机访问地址
     */
    @Value("${application.file.domain}")
    public String domain;

    /**
     * 上传文件存储在本地的根路径
     */
    @Value("${application.file.path}")
    private String localFilePath;

    @Value("${application.file.nameMaxLength}")
    private Integer fileNameMaxLength;

    @Value("${application.file.maxSize}")
    private Integer maxSize;

    @Value("${server.servlet.context-path}")
    private String contextPath;


    /**
     * 文件上传
     * @param file
     * @return
     */
    public R<String> uploadFile(MultipartFile file) {
        try {
            String fileName=file.getOriginalFilename();
            if (fileName.length() > fileNameMaxLength) {
                throw new ServiceException("文件名过长");
            }

            String extension=assertAllowed(file, MimeTypeUtils.IMAGE_EXTENSION);

            String newFileName = DateUtil.format(DateUtil.date(), "yyyy/MM/dd") + "/" + RandomUtil.randomNumbers(6) + "." + extension;

            File desc = getAbsoluteFile(localFilePath, newFileName);
            file.transferTo(desc);



            return R.ok(domain + contextPath + localFilePrefix+"/" + newFileName);
        } catch (IOException e) {
            e.printStackTrace();
            return R.fail("上传失败");
        }
    }


    public String assertAllowed(MultipartFile file, String[] allowedExtension) {
        long size = file.getSize();
        if (maxSize != -1 && size > (maxSize* 1024 * 1024)) {
            throw new ServiceException("文件不可超过"+maxSize+"M");
        }

        String extension = FileNameUtil.extName(file.getOriginalFilename());
        if (allowedExtension != null && !StrUtil.equalsAnyIgnoreCase(extension, allowedExtension)) {
            if (allowedExtension == MimeTypeUtils.CAD_EXTENSION) {
                throw new ServiceException( "只允许上传CAD文件类型");
            }else if(allowedExtension == MimeTypeUtils.JSON_EXTENSION) {
                throw new ServiceException( "只允许上传JSON文件类型");
            } else {
                throw new ServiceException( "非法文件类型");
            }
        }
        return extension;
    }

    public  File getAbsoluteFile(String uploadDir, String fileName) throws IOException {
        File desc = new File(uploadDir + File.separator + fileName);

        if (!desc.exists()) {
            if (!desc.getParentFile().exists()) {
                desc.getParentFile().mkdirs();
            }
        }
        return desc.isAbsolute() ? desc : desc.getAbsoluteFile();
    }
}
